package com.wushi.lenovo.asia5b.app_di.login.presenter;

import android.annotation.SuppressLint;

import com.mvp.base.NetParams;
import com.mvp.base.model.ResultModel;
import com.mvp.helper.AbsCrashHelper;
import com.mvp.helper.WCallBack;
import com.mvp.networking.CustomThrowable;
import com.wushi.lenovo.asia5b.app_config.CommonConstant;
import com.wushi.lenovo.asia5b.app_config.UserRepository;
import com.wushi.lenovo.asia5b.app_di.login.mvpview.RegisterActivityView;
import com.wushi.lenovo.asia5b.app_di.other.presenter.CodePresenter;
import com.wushi.lenovo.asia5b.app_event.FacebookEvent;
import com.wushi.lenovo.asia5b.app_event.LoginEvent;
import com.wushi.lenovo.asia5b.app_http.ApiService;
import com.wushi.lenovo.asia5b.app_model.other.CacheType;
import com.wushi.lenovo.asia5b.app_model.other.UserInfo;
import com.wushi.lenovo.asia5b.app_model.profile.CountryModel;
import com.wushi.lenovo.asia5b.app_model.result.LoginResModel;
import com.wushi.lenovo.asia5b.app_utils.helper.CacheHelper;

import org.greenrobot.eventbus.EventBus;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.inject.Inject;

import io.reactivex.Observable;
import io.reactivex.ObservableSource;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;

/**
 * Created by zhangyuncai on 2018/11/28.
 */
public class RegisterActivityPresenter extends CodePresenter<RegisterActivityView> {


    @Inject
    public RegisterActivityPresenter(ApiService apiService) {
        super(apiService);
    }


    public void checkEmailByRegister(String email) {
        baseSubscribe(apiService.checkEmailByRegister(email),
                new NetParams(false, false, false),
                validModelResultModel -> {
                    getView().checkEmailByRegisterResult(validModelResultModel, email);
                });
    }

    public void checkMobileByRegister(String mobile, String coutry_id) {
        baseSubscribe(apiService.checkMobileByRegister(mobile, coutry_id),
                new NetParams(false, false, false),
                validModelResultModel -> {
                    getView().checkMobileByRegisterResult(validModelResultModel, mobile);
                });
    }

    //获取国家列表
    public void getCountrys() {
        CacheHelper.getCountrys(new WCallBack<List<CountryModel>>() {
            @Override
            public void callback(List<CountryModel> countryModels) {
                getView().getCountrysResult(countryModels);
            }
        }, CacheType.LOCAL);
    }

    public void sendCode(String mobile_num, String calling_code) {
        super.sendCode(mobile_num, calling_code, CodeType.REGISTER);
    }

    public final Map<Integer, String> toastMsgMap = new HashMap<>();// 1->注册成功 2->注册失败 3->登录失败 4->登录成功

    @SuppressLint("CheckResult")
    public void register(Map<String, Object> map) {
        toastMsgMap.clear();
        Disposable subscribe = apiService.register(map)
                //注册成功
                .flatMap(new Function<ResultModel<LoginResModel>, ObservableSource<ResultModel<LoginResModel>>>() {
                    @Override
                    public ObservableSource<ResultModel<LoginResModel>> apply(ResultModel<LoginResModel> registResModelResultModel) throws Exception {
                        if (registResModelResultModel.isSuccess()) {
                            FacebookEvent.Companion.register();
                            toastMsgMap.put(1, registResModelResultModel.getMsg());
                            return Observable.just(registResModelResultModel);
                        }
                        toastMsgMap.put(2, registResModelResultModel.getMsg());
                        return Observable.error(new CustomThrowable(registResModelResultModel.getMsg()));
                    }
                })
                //登录成功
                .flatMap(new Function<ResultModel<LoginResModel>, ObservableSource<ResultModel<UserInfo>>>() {
                    @Override
                    public ObservableSource<ResultModel<UserInfo>> apply(ResultModel<LoginResModel> registResModelResultModel) throws Exception {
                        return apiService.getUserInfo(registResModelResultModel.getData().getMemberId())
                                .map(new Function<ResultModel<UserInfo>, ResultModel<UserInfo>>() {
                                    @Override
                                    public ResultModel<UserInfo> apply(ResultModel<UserInfo> userInfoResultModel) throws Exception {
                                        if (userInfoResultModel.isSuccess() && userInfoResultModel.getData() != null) {
                                            //保存userToken
                                            userInfoResultModel.getData().setUserToken(registResModelResultModel.getData().getAccess_token());
                                        }
                                        return userInfoResultModel;
                                    }
                                });
                    }
                })
                .flatMap(new Function<ResultModel<UserInfo>, ObservableSource<ResultModel<UserInfo>>>() {
                    @Override
                    public ObservableSource<ResultModel<UserInfo>> apply(ResultModel<UserInfo> userInfoResultModel) throws Exception {
                        if (userInfoResultModel.isSuccess()) {
                            return Observable.just(userInfoResultModel);
                        }
                        toastMsgMap.put(3, userInfoResultModel.getMsg());
                        return Observable.error(new CustomThrowable(userInfoResultModel.getMsg()));
                    }
                })
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .doOnSubscribe(disposable -> {
                    if (loadMvpView != null) {
                        loadMvpView.showLoadingBar(null);
                    }
                })
                .doAfterTerminate(() -> {
                    if (loadMvpView != null) {
                        loadMvpView.dismissLoadingBar(null);
                    }
                })
                .subscribe(userInfoResultModel -> {
                    if (userInfoResultModel.isSuccess() && userInfoResultModel.getData() != null) {
                        UserRepository.setUserInfo(userInfoResultModel.getData());
                        EventBus.getDefault().post(new LoginEvent(CommonConstant.LOGIN_SUCCESS));
                        toastMsgMap.put(4, "");
                        getView().registerResult(toastMsgMap);
                    }
                }, throwable -> {
                    getView().registerResult(toastMsgMap);
                    AbsCrashHelper.postCatchedException(throwable);
                });
        composite.add(subscribe);


    }

}